package com.epsoft.odin7cj.flow.bpo._impl.form;

import java.util.HashMap;
import java.util.Map;

import org.camunda.bpm.engine.FormService;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.epsoft.odin7cj.flow.bpo.form.FormBPO;
import com.epsoft.odin7cj.flow.model.form.FixedForm;

/**  
 * 表单BOP实现类 
 * @author 胡义振  
 * @date 2018年10月16日  
*/
@Service 
public class FormBPOImpl implements FormBPO {

	@Autowired
	private FormService formService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private HistoryService historyService;
	
	/**
	 * DESC: 获取表单数据
	 * @auther 胡义振
	 * @date 2020年6月30日
	 * @param fixedForm
	 * @param dynamicFormData
	 * @param extFormData
	 * @return 
	 * @return
	 */
	@Override
	public Map<String, Object> getFormData(FixedForm fixedForm, String dynamicFormData, String extFormData)  throws Exception{
		Map<String, Object> paramMap = new HashMap<String,Object>();
		// 获取动态表单数据
		if(dynamicFormData!=null && !"".equals(dynamicFormData)) {
			paramMap = (Map<String, Object>) JSON.parse(dynamicFormData);
		}
		// 获取外部表单数据
		else if(extFormData!=null && !"".equals(extFormData)) {
			paramMap.put("extFormData", extFormData);
		}
		// 获取审核数据
		else if(fixedForm!=null) {
			paramMap.put("auditOption", fixedForm.getAuditOption());
			paramMap.put("auditResult", fixedForm.getAuditResult());
		}
		return paramMap;
	}

	/**
	 * DESC: 获取表外置表单ID
	 * @auther 胡义振
	 * @date 2020年6月30日
	 * @param taskId
	 * @return
	 * @throws Exception 
	 * @return
	 */
	@Override
	public String getTaskFormKey(String taskId) throws Exception {
		System.out.println("\n taskId:"+taskId);
		
		HistoricTaskInstance task = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		
//		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		
		System.out.println("\n task:"+task);
		
		// 流程实例ID
		String processInstanceId = task.getProcessInstanceId();
		// 流程定义ID
		String processDefinitionId = task.getProcessDefinitionId();
		// 当前节点ID
		String currActivityId = task.getTaskDefinitionKey();
//		String startFormKey = formService.getStartFormKey(processDefinitionId);
		String taskFormId = formService.getTaskFormKey(processDefinitionId, currActivityId);
//		Object startForm = formService.getRenderedStartForm(processDefinitionId, "juel");
//		Object taskForm = formService.getRenderedTaskForm(taskId, "juel");
		return taskFormId;
	}



}
